package com.itheima.tanhua.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.tanhua.api.db.QuestionServiceApi;
import com.itheima.tanhua.api.db.UserInfoServiceApi;
import com.itheima.tanhua.api.mongo.FriendServiceApi;
import com.itheima.tanhua.api.mongo.TanhuaServiceApi;
import com.itheima.tanhua.api.mongo.UserLocationApi;
import com.itheima.tanhua.exception.ConsumertException;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhuan.pojo.db.UserInfo;
import com.itheima.tanhuan.pojo.mongo.RecommendUser;
import com.itheima.tanhuan.pojo.mongo.UserLocation;
import com.itheima.tanhuan.pojo.mongo.Visitors;
import com.itheima.tanhuan.vo.mongo.NearUserVo;
import com.itheima.tanhuan.vo.mongo.TodayBestVo;
import com.itheima.tanhuan.vo.mongo.UserLocationVo;
import com.mongodb.client.model.geojson.Point;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {
    @DubboReference
    UserInfoServiceApi userInfoServiceApi;
    @DubboReference
    TanhuaServiceApi tanhuaServiceApi;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @DubboReference
    QuestionServiceApi questionServiceApi;
    @DubboReference
    FriendServiceApi friendServiceApi;
    @DubboReference
    UserLocationApi userLocationApi;


    //佳人详情

    /**
     * @param userId 佳人id
     * @return
     */
    public TodayBestVo personalInfo(Long userId) {
        TodayBestVo todayBestVo = new TodayBestVo();
        //根据登录者和佳人信息来查找缘分值
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("UID"));
        RecommendUser fateValue = tanhuaServiceApi.findFateValue(uid, userId);

        //根据佳人id找到佳人信息，封装对象返回
        UserInfo userInfoServiceApiById = userInfoServiceApi.findById(userId);
        BeanUtil.copyProperties(userInfoServiceApiById, todayBestVo);
        Long score = fateValue.getScore();
        todayBestVo.setFateValue(Convert.toInt(score));

        //谁查看了我的记录
        tanhuaServiceApi.upset(uid,userId,score);
        return todayBestVo;
    }

    /**
     * 查看问题
     *
     * @param userId
     * @return
     */
    public String strangerQuestions(Long userId) {
        return questionServiceApi.strangerQuestions(userId);
    }

    @Autowired
    HuanXinTemplate huanXinTemplate;

    public void replyQuestions(Long userId, String reply) {
     /*   Map<String,String>map=new HashMap<>();
        //返回个人信息和陌生人的环信
        String myid = stringRedisTemplate.opsForValue().get("UID");
        UserInfo userInfoServiceApiById = userInfoServiceApi.findById(Convert.toLong(myid));
        map.put("userId",myid);
        map.put("huanXinId",Constants.HX_USER_PREFIX+myid);
        map.put("nickname",userInfoServiceApiById.getNickname());
        map.put("strangerQuestion",questionServiceApi.strangerQuestions(userId));
        map.put("reply",reply);
        String jsonStr= JSONUtil.toJsonStr(map);
        huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX+userId,jsonStr);*/
        //1、构造消息数据
        Long currentUserId = Convert.toLong(stringRedisTemplate.opsForValue().get("UID"));
        UserInfo userInfo = userInfoServiceApi.findById(currentUserId);
        Map map = new HashMap();
        map.put("userId", currentUserId);
        map.put("huanXinId", Constants.HX_USER_PREFIX + currentUserId);
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", strangerQuestions(userId));
        map.put("reply", reply);
        String message = JSON.toJSONString(map);
        //2、调用template对象，发送消息
        Boolean aBoolean = huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX + userId, message);//1、接受方的环信id，2、消息
        if (!aBoolean) {
            throw new ConsumertException("发送失败");
        }
    }

    /**
     * 用户id找佳人推荐，取佳人列表，找佳人详情，封装返回，新用户设置默认。
     */
    public List<TodayBestVo> queryCardsList() {
        //1.获得当前登录者id,已经喜欢的用户
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("UID"));
        List<Long> findLikeUserIds = tanhuaServiceApi.findLikeUser(uid);
        //2.找到推荐用户的id,排除以喜欢的用户
        List<Long> findRecommentUserIds = tanhuaServiceApi.findRecommentUserId(uid, findLikeUserIds);
        //3.封装对象返回值
        Map<Long, UserInfo> userInfoServiceApiByIds = userInfoServiceApi.findByIds(findRecommentUserIds, null);
        List<TodayBestVo> todayBestVos = new ArrayList<>();
        for (Long findLikeUserId : findRecommentUserIds) {
            TodayBestVo todayBest = TodayBestVo.getTodayBest(userInfoServiceApiByIds.get(findLikeUserId));
            todayBestVos.add(todayBest);
        }
        return todayBestVos;
    }

    /*
     *背景：喜欢佳人
     * 保存到mangodb的like
     * 查询是否相互喜欢
     * 是，保存喜欢在redis中,删除不喜欢的数据。
     * 不是，
     */
    public void likeUser(Long likeUserId) {
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("UID"));
        //保存喜欢记录
        Boolean isSave = tanhuaServiceApi.saveUserLike(uid, likeUserId, true);
        Boolean isDouble = tanhuaServiceApi.isDoubleLike(uid, likeUserId);
        if (isDouble) {
            Boolean isFriends = friendServiceApi.createFriend(likeUserId, uid);
        }
        //todo 优化
        stringRedisTemplate.opsForValue().set(Constants.MOVEMENT_LOVE_HASHKEY + uid, Convert.toStr(likeUserId));
        stringRedisTemplate.delete(Constants.MOVEMENT_LOVE_HASHKEY + uid);
    }

    public void notLikeUser(Long likeUserId) {
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("UID"));
        //保存不喜欢记录
        Boolean isSave = tanhuaServiceApi.saveUserLike(uid, likeUserId, false);
        //如果是朋友关系
        if (friendServiceApi.isFriend(uid, likeUserId)) {
            Boolean isNotFriend = friendServiceApi.isNotFriend(uid, likeUserId);
            huanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + uid, Constants.HX_USER_PREFIX + likeUserId);
        }

    }
//搜索附近

    /**
     * 以登录者的地址画⚪，返回用户信息
     *
     * @param gender   性别
     * @param distance 距离
     * @return
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("UID"));
        UserLocationVo userLocationVo = userLocationApi.findLocaltionByUid(uid);
        Double longitude = Convert.toDouble(userLocationVo.getLongitude());
        Double latitude = Convert.toDouble(userLocationVo.getLatitude());
        //1.以自己为点，半径为线，圈为范围，
        List<Long> ids =userLocationApi.getIds(longitude,latitude,distance,uid);


        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (Long id : ids) {
            UserInfo userInfo = userInfoServiceApi.findById(id);
            if (userInfo.getGender().equals(gender)){
                NearUserVo init = NearUserVo.init(userInfo);
                nearUserVoList.add(init);
            }
        }

        return nearUserVoList;
    }
}
